//index.js
//获取应用实例
var app = getApp();

Page({
  data: {
    scrollTop: {
      scroll_top: 0,
    },
    showPulldown: false,
    isFixed: false,
    isshow_subsidy: true,
    minprice: '',
    maxprice: '',
    redTriangle: false,
    isShow0: false,
    isShow1: false,
    isShow2: false,
    sort: 0,
    cname: "",
    sortName: "默认",
    currentTab: 0,
    currentTab2: 0,
    hiddenLoading: false,
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    from_uid: 0,
    nickname: '',
    keyword: '',
    memberid: 0,
    datalock: false,
    uri: "list",
    searchkey: "",
    showAnimation: false,
    globalset: {

    },
    homeskinid: -1,
    duration: 100,
    "banner": [
    ],
    commodity: [

    ],
    goodCarousel: [

    ],
    goodCarousel2: [

    ],
    imgmenu: [
    ],
    imgmenu2: [
    ],
    imgmenu3: [

    ],
    helpmenu: [
      {
        "img": '../../images/activity3.png',
        "name": '省钱看这里',
        "url": '../savemoney-help/index'
      },
      {
        "img": '../../images/activity4.png',
        "name": '赚钱看这里',
        "url": '../makemoney-help/index'
      }
    ],
    activitymenu: [
      {
        "img": '../../images/pgziying.png',
        "name": 'ziying',
        "url": '../savemoney-help/index'
      },
      {
        "img": '../../images/9.9.png',
        "name": '9.9',
        "url": '../makemoney-help/index'
      }
    ],
  },

  onLoad: function (options) {

    this.getpgcname();
    //this.checkClipboard();
  
    //app.setTabBar();
    var $this = this;
    //扫二维码进来的推荐人ID获取
    if (typeof options != "undefined" && typeof options.scene != "undefined") {
      wx.setStorage({
        key: "from_uid",
        data: options.scene
      });
      this.setData({
        from_uid: options.scene,
        datalock: false
      });

    }



    if (typeof options != "undefined" && typeof options.from_uid != "undefined") {
      wx.setStorage({
        key: "from_uid",
        data: options.from_uid
      });
      this.setData({
        from_uid: options.from_uid,
        datalock: false
      });
    }
    this.getGlobalSet();


  },
  initIndex: function () {
    var $this = this;
    
    $this.goodList(1);

    var memberinfo = wx.getStorageSync('memberinfo');
    var globalset = wx.getStorageSync('globalset');
    $this.setData({
      memberinfo: memberinfo,
      commission: 0,
      datalock: false
    });
    //计算总的佣金比例
    var total_commission = 0;
    if (globalset.memberlevel != undefined && globalset.memberlevel.length != undefined) {
      for (var i = 0; i < globalset.memberlevel.length; i++) {
        //当前会员类型的等级佣金比例
        if (globalset.memberlevel[i].type == memberinfo.type && globalset.memberlevel[i].name == memberinfo.level) {
          total_commission = parseFloat(globalset.memberlevel[i].myteam_credit2) + parseFloat(globalset.memberlevel[i].myleader1_credit2) + parseFloat(globalset.memberlevel[i].myleader2_credit2);
          //换成只取1级佣金的比例
          total_commission = parseFloat(globalset.memberlevel[i].myteam_credit2);
      
          $this.setData({
            commission: total_commission,
            datalock: false
          });
        }
      }
    }
    if (memberinfo.type == 0) {
      if (globalset.isopen_subsidy == 0) {
        $this.setData({
          isshow_subsidy: false
        });
      }
     
      total_commission = parseFloat(globalset.subsidy);
      $this.setData({
        commission: total_commission,
        datalock: false
      });
    }

    if (globalset.isshow_subsidy == 0) {
      $this.setData({
        isshow_subsidy: false
      });
    }
  },
  getGlobalSet: function (e) {
    var $this = this;
    app.util.request({
      url: 'entry/wxapp/Global',
      showLoading: false,
      data: {
        "m": 'nets_haojk'
      },
      method: 'post',
      success: function (response) {
        var globalset = response.data.data;
        $this.setData({
          hiddenLoading: true
        });
        $this.setData({
          globalset: globalset,
          homeskinid: globalset.homeskinid
        });
        wx.setStorage({
          key: "globalset",
          data: globalset
        });
        //banner
        var banner_str = globalset.banner;
        var banner_json = JSON.parse(banner_str);
        if (banner_json != undefined && banner_json.list != null && banner_json.list != undefined && typeof banner_json.list != undefined && banner_json.list != null && banner_json.list != '') {
          $this.setData({
            banner: banner_json.list,
            datalock: false
          });
        }
        //图标菜单
        var newhead_menu_json = [];
        var head_menu_str = globalset.head_menu;
        var head_menu_json = JSON.parse(head_menu_str);
    

        if (head_menu_json != undefined && head_menu_json.list != null && head_menu_json.list != undefined && typeof head_menu_json.list != undefined && head_menu_json.list != null && head_menu_json.list != '') {
          var menulen = head_menu_json.list.length;
          for (var i = 0; i < 8; i++) {
            newhead_menu_json.push(head_menu_json.list[i])
          }


          $this.setData({
            imgmenu: newhead_menu_json,
            datalock: false

          });
          var imgmenu2 = new Array();
          for (var i = 8; i < 16; i++) {
            imgmenu2.push(head_menu_json.list[i]);
          }
          $this.setData({
            imgmenu2: imgmenu2,
            datalock: false
          });
          if (e) {
            // $this.setData({
            //   imgmenuAll: head_menu_json.list,
            //   datalock: false
            // });
          }
          // $this.setData({
          //   imgmenuAll: head_menu_json.list,
          //   datalock: false
          // });


          var imgmenu22 = new Array();
          for (var i = 16; i < menulen; i++) {
            imgmenu22.push(head_menu_json.list[i]);
          }
          $this.setData({
            imgmenu22: imgmenu22,
            datalock: false
          });
          var imgmenu222 = new Array();
          for (var i = 24; i < menulen; i++) {
            imgmenu222.push(head_menu_json.list[i]);
          }
          $this.setData({
            imgmenu222: imgmenu222,
            datalock: false
          });
        }

        //图片魔方菜单
        var picture_menu_str = globalset.picture_menu;
        var picture_menu_json = JSON.parse(picture_menu_str);
        var picture_menu = new Array();
        var pmenu = new Object();

        if (picture_menu_json != undefined && typeof picture_menu_json.list != undefined && picture_menu_json.list != null && picture_menu_json.list != null && picture_menu_json.list.length >= 4) {
          pmenu.img1 = typeof picture_menu_json.list[0].img == "undefined" ? "" : picture_menu_json.list[0].img;
          pmenu.name1 = typeof picture_menu_json.list[0].name == "undefined" ? "" : picture_menu_json.list[0].name;
          pmenu.url1 = typeof picture_menu_json.list[0].url == "undefined" ? "" : picture_menu_json.list[0].url;

          pmenu.img2 = typeof picture_menu_json.list[1].img == "undefined" ? "" : picture_menu_json.list[1].img;
          pmenu.name2 = typeof picture_menu_json.list[1].name == "undefined" ? "" : picture_menu_json.list[1].name;
          pmenu.url2 = typeof picture_menu_json.list[1].url == "undefined" ? "" : picture_menu_json.list[1].url;
          pmenu.img3 = typeof picture_menu_json.list[2].img == "undefined" ? "" : picture_menu_json.list[2].img;
          pmenu.name3 = typeof picture_menu_json.list[2].name == "undefined" ? "" : picture_menu_json.list[2].name;
          pmenu.url3 = typeof picture_menu_json.list[2].url == "undefined" ? "" : picture_menu_json.list[2].url;
          pmenu.img4 = typeof picture_menu_json.list[3].img == "undefined" ? "" : picture_menu_json.list[3].img;
          pmenu.name4 = typeof picture_menu_json.list[3].name == "undefined" ? "" : picture_menu_json.list[3].name;
          pmenu.url4 = typeof picture_menu_json.list[3].url == "undefined" ? "" : picture_menu_json.list[3].url;
        } else {
          pmenu.img1 = "";
          pmenu.name1 = "";
          pmenu.url1 = "";
          pmenu.img2 = "";
          pmenu.name2 = "";
          pmenu.url2 = "";
          pmenu.img3 = "";
          pmenu.name3 = "";
          pmenu.url3 = "";
          pmenu.img4 = "";
          pmenu.name4 = "";
          pmenu.url4 = "";
        }
        picture_menu.push(pmenu);
        $this.setData({
          imgmenu3: picture_menu,
          datalock: false
        });

        //活动图片
        var picture_menu2_str = globalset.picture_menu2;
        var picture_menu2_json = JSON.parse(picture_menu2_str);
        if (picture_menu2_json != undefined && picture_menu2_json.list != null && picture_menu2_json.list != undefined && typeof picture_menu2_json.list != undefined && picture_menu2_json.list != null && picture_menu2_json.list != '') {
          // $this.setData({
          //   activitymenu: picture_menu2_json.list,
          //   datalock: false
          // });

        }
        //广告图片
        var ad_menu_str = globalset.ad_menu;
        var ad_menu_json = JSON.parse(ad_menu_str);
        if (ad_menu_json != undefined && ad_menu_json.list != null && ad_menu_json.list != undefined && typeof ad_menu_json.list != undefined && ad_menu_json.list != null && ad_menu_json.list != '') {
          $this.setData({
            admenu: ad_menu_json.list,
            datalock: false
          });

        }

        $this.setData({
          hiddenLoading: true
        });
        $this.getMember();

      }
    });

  },
  getMember: function () {
    var that = this;
    app.getUserInfo(function (userInfo) {
      //更新数据
      app.util.getUserInfo(function (response) {

        response.memberInfo.nickname = userInfo.nickName;
        response.memberInfo.avatar = userInfo.avatarUrl;
        response.memberInfo.city = userInfo.city;
        response.memberInfo.country = userInfo.country;
        response.memberInfo.province = userInfo.province;
        response.memberInfo.gender = userInfo.gender;
        that.addMember(response.memberInfo);
      });
    });
    // 页面渲染完成
  },

  addMember: function (userInfo) {
    var $this = this;
    app.util.request({
      url: 'entry/wxapp/AddMember',
      showLoading: false,
      data: {
        "m": 'nets_haojk',
        "from_uid": this.data.from_uid,
        "nickname": userInfo.nickname,
        "avatar": userInfo.avatar,
        "city": userInfo.city,
        "country": userInfo.country,
        "province": userInfo.province,
        "gender": userInfo.gender,
      },
      method: 'post',
      success: function (response) {
        //首页存储会员对象到缓存，其他页面直接读取缓存即可
        wx.setStorage({
          key: "memberinfo",
          data: response.data.data
        });
        $this.setData({
          memberid: response.data.data.memberid,
          nickname: response.data.data.nickname,
          datalock: false
        });
        //取会员对象的方式
        wx.getStorage({
          key: 'memberinfo',
          success: function (res) {
          }
        });

        $this.initIndex();

      }
    });
  },

  getpgcname: function () {
    var $this=this;
    app.util.request({
      url: 'entry/wxapp/Pgcname',
      showLoading: false,
      data: {
        "m": 'nets_haojk'
      },
      method: 'post',
      success: function (response) {
       
        $this.setData({
          imgmenuAll: response.data.data,
            datalock: false
          });
      }
    });
  },
  bycname: function (e) {
    var cname = e.currentTarget.dataset.url.split("=")[1];
    wx.setStorageSync("cname_show", e.currentTarget.dataset.cname);
    wx.setStorageSync("cname", cname);
    wx.setStorageSync("searchkey", "");
    var thiscname = cname;


    thiscname.replace(/(^\s*)|(\s*$)/g, "");
   


    if (thiscname == "2小时跑单") {
      wx.navigateTo({
        url: "../seniorityTwohours/index",

      })

    } else if (thiscname == "全天销售榜") {
      
      wx.navigateTo({
        url: "../seniorityAlldays/index",

      })

    } else if (thiscname == "实时排行榜" || thiscname == "榜单") {
     
      //  实时排行榜
      wx.switchTab({
        url: "../seniority/index",

      })

    } else {
      wx.reLaunch({
        url: e.currentTarget.dataset.url
      })
    }


  },
  //根据点击的自定义的sort加载商品
  bysortcname:function(e){
    //自营
    if (e.currentTarget.dataset.cname=="ziying"){
    this.setData({
      sort: 99,
      minprice:"",
      maxprice:""
    });
    }else if (e.currentTarget.dataset.cname == "9.9") {
      this.setData({
        minprice: 0.1,
        maxprice:9.9,
        sort:0
      });
    }else{
      this.setData({
        cname: e.currentTarget.dataset.cname
      });
    }
    this.goodList(1);
  },
  ////不跳转到精选页面
  bycname1: function (e) {
    var $this = this;
    wx.getSystemInfo({
      success: function (res) {
        $this.setData({
          scrollHeight: res.windowHeight
        });
      }
    });
    
    //判断不为精选
    var cname = "";
    if (e.currentTarget.dataset.url) {

      cname = e.currentTarget.dataset.url.split("=")[1];
    }
    cname = e.currentTarget.dataset.cname;
    this.setData({
      cname_show: e.currentTarget.dataset.cname
    });
   
    //判断是否为精品请求
    if (e.currentTarget.dataset.isjinpin == 1) {
     
      this.setData({
        cname: cname,
        uri: "list",
        keyword: '',

      });
      
    } else if (e.currentTarget.dataset.ishavekeyword == 1) {

      this.setData({
        cname: "",
        uri: "listbysearch",
        keyword: $this.data.keyword,

      });
    } else {
      this.setData({
        cname: cname,
        uri: "listbycname",
        keyword: '',
      });
    }
   
    this.setData({
      cname: cname,
      uri: "listbycname",
      keyword: '',
    });
    wx.setStorage({
      key: "cname",
      data: e.currentTarget.dataset.cname
    });


    this.setData({
      commodity: [],
      datalock: false
    });
    wx.setStorage({
      key: "searchkey",
      data: ""
    });

    this.goodList(1);
  },

  limittimeMore: function (e) {
    wx.setStorageSync("searchkey", "");
    wx.setStorageSync("limittime", 1);
    wx.setStorageSync("realtime", "");
    wx.navigateTo({
      url: "../search/index",
    })
  },
  realtimeMore: function (e) {
    wx.setStorageSync("searchkey", "");
    wx.setStorageSync("limittime", "");
    wx.setStorageSync("realtime", "1");
    wx.navigateTo({
      url: "../search/index",
    })
  },
  bindKeyInput: function (e) {
   
    var value = e.detail.value;
    var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
    var objExp = new RegExp(Expression);
    if (objExp.test(value) == true) {
      //是URL
      if (value.indexOf(".html") > 0) {
        value = value.split('?')[0];
        var valuearr = value.split("/");
        value = valuearr[valuearr.length - 1];
        value = value.replace(".html", "");
      }
      if (value.indexOf("sku=") > 0) {
        value = value.split('sku=')[1];
        var valuearr = value.split("&");
        value = valuearr[0];
      }
    }

    
    if (e.currentTarget.dataset.ishavekeyword == 1) {
      this.setData({
        searchkey: value
      });
      this.setData({
        keyword: value,
        cname: "",
        uri: "listbysearch"
      });
     
    }

  },
  onShareAppMessage: function (res) {
    var memberinfo = wx.getStorageSync("memberinfo");
    if (res.from === 'button') {
    }

    return {
      title: this.data.globalset.title,
      path: '/haojk/pages/pingou/index?from_uid=' + memberinfo.memberid + '&from_nickname=' + memberinfo.nickname + '&type=' + memberinfo.type + '&homeskinid=' + memberinfo.homeskinid,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }

  },
  goTopFun: function (e) {
    var _top = this.data.scrollTop.scroll_top;//发现设置scroll-top值不能和上一次的值一样，否则无效，所以这里加了个判断 
    if (_top == 1) {
      _top = 0;
    } else {
      _top = 1;
    }
    this.setData({
      'scrollTop.scroll_top': _top
    });
  },

  goodList: function (page, t, callback, goodstype) {
    var $this = this;
    var limittime = 1;
    var realtime = 1;
    if (t == "limittime") {
      realtime = "";
    } else if (t == "realtime") {
      limittime = "";
    } else {
      //  $this.setData({canBottomRefresh:true});
      limittime = "";
      realtime = "";
    }
    if ($this.data.datalock) {
      //return false;
    }
    $this.setData({
      page: page,
      datalock: true,
    });
   
    app.util.request({
      url: 'entry/wxapp/PgGoods',
      showLoading: false,
      data: {
        m: 'nets_haojk',
        page: page,
        uri: $this.data.uri,
        limittime: limittime,
        realtime: realtime,
        keyword: $this.data.keyword,
        sort: $this.data.sort,
        keyword: $this.data.keyword,
        cname: $this.data.cname,
        minprice: $this.data.minprice,
        maxprice: $this.data.maxprice,
        goodstype: goodstype
      },
      method: 'post',
      success: function (response) {
        if (typeof callback == 'function') {
          callback(response.data.data);
          $this.setData({
            datalock: false
          });
        } else {
          var goods = $this.data.commodity;
          if (page == 1) {
            goods = new Array();
          }
          var shishigoods = Array();
          var jinrigoods = Array();
          if (t == "limittime") {

            goods = $this.data.goodCarousel;
          } else if (t == "realtime") {
            goods = $this.data.goodCarousel2;
          }
          if (response.data.data) {
            var row = 0;
            for (var i in response.data.data) {
              row++;
              if ($this.data.commission == 0) {
                response.data.data[i].wlPrice_after1 = response.data.data[i].discount;
              } else {
                response.data.data[i].wlPrice_after1 = response.data.data[i].wlPrice_after * (response.data.data[i].wlCommissionShare / 100) * ($this.data.commission / 100) * 0.9;
                if (response.data.data[i].wlPrice_after1 > 0)
                  response.data.data[i].wlPrice_after1 = response.data.data[i].wlPrice_after1.toFixed(2);



              }
              if (row <= 6 && page == 1) {
                shishigoods.push(response.data.data[i]);
              } else if (row > 6 && row <= 12 && page == 1) {
                jinrigoods.push(response.data.data[i]);
              } else {
                goods.push(response.data.data[i]);
              }
            }
          }
          if (t == "limittime") {
            $this.setData({
              goodCarousel: goods,
              datalock: false
            });
          } else if (t == "realtime") {
            $this.setData({
              goodCarousel2: goods,
              datalock: false
            });
            
          } else {
            if (page == 1) {
              $this.setData({
                goodCarousel: shishigoods,
                datalock: false
              });

              $this.setData({
                goodCarousel2: jinrigoods,
                datalock: false
              });
            }


            $this.setData({
              commodity: goods,
              datalock: false
            });


          }
        }


      }
    });
  },

  //事件处理函数
  skiptodetail: function (e) {

    var skuId = e.currentTarget.dataset.skuid;
    for (var i = 0; i < this.data.commodity.length; i++) {
      if (this.data.commodity[i].skuId == skuId) {
        var good = this.data.commodity[i];
        wx.setStorage({
          key: "good",
          data: good
        });
      }
    }

    for (var i = 0; i < this.data.goodCarousel.length; i++) {
      if (this.data.goodCarousel[i].skuId == skuId) {
        var good = this.data.goodCarousel[i];
        wx.setStorage({
          key: "good",
          data: good
        });
      }
    }
    for (var i = 0; i < this.data.goodCarousel2.length; i++) {
      if (this.data.goodCarousel2[i].skuId == skuId) {
        var good = this.data.goodCarousel2[i];
        wx.setStorage({
          key: "good",
          data: good
        });
      }
    }





    wx.navigateTo({
      url: '../detailPingtuan/index?skuId=' + skuId
    })
  },
  onReachBottom: function () {

    var $this = this;

    var page = $this.data.page + 1;
    var second_height = $this.data.second_height * page;
    $this.setData({ second_height: second_height });
    $this.goodList(page);

  },
  priceSort: function () {
    var $this = this;

    //关闭下拉框
    if ($this.data.isShow2) {
      $this.setData({
        isShow0: false,
        isShow1: false,
        isShow2: false,
        curHdIndex: 3,
      })
    } else if (!$this.data.isShow2) {
      $this.setData({
        isShow0: false,
        isShow1: false,
        isShow2: false,
        curHdIndex: 3,

      })
    }
    $this.goodList(1);
  },

  changeMaxprice: function (e) {
    this.setData({
      maxprice: e.detail.value
    })

  },
  changeMinprice: function (e) {
    this.setData({
      minprice: e.detail.value
    })

  },
  checkClipboard: function () {
    
    var $that = this;
    wx.getClipboardData({
      success: function (res) {
       
        if (res.data != '' && res.data != undefined && res.data != null) {
          res.data = res.data.trim();
         
          var value = res.data;
          var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
          var objExp = new RegExp(Expression);
          if (objExp.test(value) == true) {
            //是URL
            if (value.indexOf(".html") > 0) {
              value = value.split('?')[0];
              var valuearr = value.split("/");
              value = valuearr[valuearr.length - 1];
              value = value.replace(".html", "");
            }
            if (value.indexOf("sku=") > 0) {
              value = value.split('sku=')[1];
              var valuearr = value.split("&");
              value = valuearr[0];
            }
          }
          
          if (value != "") {
            wx.showModal({
              title: '检测到剪切版内容',
              content: res.data,

              showCancel: true,
              confirmText: '去搜索',
              success: function (res) {
                if (res.confirm) {
                  
                  wx.setStorageSync("searchkey", value);
                  wx.setClipboardData({
                    data: '',
                    success: function (res) {
                      wx.getClipboardData({
                        success: function (res) {
                        
                        }
                      })
                    }
                  })
                  wx.navigateTo({
                    url: "../search/index",

                  })

                } else if (res.cancel) {
                 
                }
              },
            })
          }
        }
      }

    })
  },
  topDistance: function (e) {
  },
  showTanchuang: function () {
    var $that = this;
    app.util.request({
      url: 'entry/wxapp/GetOrderTipInfo',
      showLoading: false,
      data: {
        m: 'nets_haojk',

      },
      method: 'post',
      success: function (response) {
      
        if (response.data.errno == 0) {
          var array = response.data.data;
          var arrayLength = array.length;
          var arrayI = Math.ceil(Math.random() * arrayLength);
          var arrayItem = '';
          setInterval(function () {
            arrayI = Math.ceil(Math.random() * arrayLength);

            arrayItem = array[arrayI];
          
            $that.setData({ tipText: arrayItem });
            if ($that.data.showAnimation) {
              if (arrayItem) {
                $that.setData({ showAnimation: false });
              }

            } else {
              if (arrayItem) {
                $that.setData({ showAnimation: true });
              }

            }

          }, 8000)



        }
      }
    })

  },
  changePullDState: function () {
    
    var $that = this;
    if ($that.data.showPulldown) {
      $that.setData({
        showPulldown: false,
      })
    } else {
      $that.setData({
        showPulldown: true,
      })
    }

  }
})
